var g_JSChart = null;
// #ifdef H5
import HQChart from '@/uni_modules/jones-hqchart2/js_sdk/umychart.uniapp.h5.js';
// #endif
// #ifndef H5
import { JSCommon } from '@/uni_modules/jones-hqchart2/js_sdk/umychart.wechat.3.0.js';
import { JSCommonHQStyle } from '@/uni_modules/jones-hqchart2/js_sdk/umychart.style.wechat.js';
// #endif
//测试数据
import HQData from '@/uni_modules/jones-hqchart2/js_sdk/umychart.NetworkFilterTest.vue.js';

function DefaultData() {}
DefaultData.GetKLineOption = function () {
  let data = {
    Type: '历史K线图',

    //窗口指标
    Windows: [
      {
        Index: 'MA'
      },
      {
        Index: 'VOL'
      }
      // { Index: "RSI" }
    ],
    IsAutoUpdate: true,
    AutoUpdateFrequency: 5000, //数据更新频率
    IsCorssOnlyDrawKLine: true,
    CorssCursorTouchEnd: true,
    IsClickShowCorssCursor: true,
    CorssCursorInfo: {
      Left: 2,
      Right: 2,
      Bottom: 1,
      IsShowCorss: true
    }, //十字光标刻度设置
    //IsFullDraw:true,

    //边框
    Border: {
      Left: 1,
      Right: 1, //右边间距
      Top: 25,
      Bottom: 55
    },

    KLine: {
      DragMode: 1,
      Right: 1, //复权 0 不复权 1 前复权 2 后复权
      Period: 0, //周期: 0 日线 1 周线 2 月线 3 年线
      PageSize: 30,
      IsShowTooltip: false,
      DrawType: 0,
      DataWidth: 10,
      MaxReqeustDataCount: 1000 //数据个数
    },

    //标题设置
    KLineTitle: {
      TextSpace: 2,
      DateTimeSpace: 5,
      NameSpace: 2,
      PeriodSpace: 2
    },

    ExtendChart: [
      {
        // Name: 'KLineTooltip'
      } //开启手机端tooltip
    ],

    //子框架设置
    Frame: [
      {
        SplitCount: 3,
        Custom: [
          {
            Type: 0,
            Position: 'right'
          },
          {
            Type: 1,
            LineDash: [3, 5],
            Position: 'left',
            IsShowLine: true,
            LineType: 1,
            PositionEx: 0,
            LineWidth: 1,
            Data: [
              {
                Value: 7.7,
                Color: 'rgb(255,0,0)',
                TextColor: 'rgb(255,255,255)', //Color:线段及文字背景色 TextColor:文字颜色
                Text: [
                  {
                    Text: '成本线'
                  },
                  {
                    Text: '价格:8.01'
                  }
                ]
              },
              {
                Value: 7.55,
                Color: 'rgb(255,185,0)',
                TextColor: 'rgb(255,255,255)' //Color:线段及文字背景色 TextColor:文字颜色
              }
            ]
          }
        ]
      },
      {
        SplitCount: 2
      },
      {
        SplitCount: 3
      }
    ],

    OverlayIndex: [
      //{Index:'BOLL', Windows:0 , IsShareY:true, },
      //{Index:'RSI', Windows:0,  },
    ]
  };

  return data;
};
DefaultData.GetMinuteOption = function () {
  var option = {
    Type: '分钟走势图', //创建图形类型

    //窗口指标
    Windows: [
      // { Index: "MACD" },
      //{ Name:"测试", Script:test2 }
    ],

    IsAutoUpdate: true, //是自动更新数据
    AutoUpdateFrequency: 5000, //数据更新频率
    DayCount: 1, //1 最新交易日数据 >1 多日走势图
    IsShowRightMenu: false, //是否显示右键菜单
    CorssCursorTouchEnd: true,
    IsFullDraw:true,

    MinuteLine: {
      // IsDrawAreaPrice:false,      //是否画价格面积图
      SplitType: 0,
    },

    //边框
    Border: {
      Left: 1, //左边间距
      Right: 1, //右边间距
      Top: 20,
      Bottom: 20
    },

    //子框架设置
    Frame: [
      {
        SplitCount: 9,
        // Custom: [
        //   {
        //     Type: 1,
        //     Position: 'left',
        //     Data: [
        //       {
        //         Increase: 0.005, // Value:刻度Y轴价格 Text:显示文本 Increase:涨幅
        //         Color: 'rgb(255,185,0)',
        //         TextColor: 'rgb(255,255,255)' //Color:线段及文字背景色 TextColor:文字颜色
        //       }
        //     ]
        //   }
        // ]
      },
      {
        SplitCount: 2
      },
      {
        SplitCount: 3
      }
    ],

    //标题设置
    MinuteTitle: {
      TextSpace: 5,
      IsShowTime: false
    },

    //扩展图形
    ExtendChart: [
      {
        // Name: 'MinuteTooltip'
      } //手机端tooltip
    ]
  };

  return option;
};
export default {
  components: {},
  data() {
    return {
      Symbol: '600000.sh',
      // this.dataList[0].goodscode
      ChartWidth: 350,
      ChartHeight: 500,
      KLine: {
        Period: 0,
        Right: 0
      }
    };
  },
  onReady() {},
  created() {},
  onShow() {
    this.init();
  },
  onHide() {
    this.ClearChart();
  },
  onUnload() {
    this.ClearChart();
  },
  methods: {
    init() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
      uni.getSystemInfo({
        // 获取手机信息
        success: res => {
          var width = res.windowWidth;
          // var height = res.windowHeight;
          this.ChartWidth = width;
          this.chartHeight = 400;
          // this.timer = setInterval(() => {
					// 	this.CreateChartRefresh()
					// }, 5000);
					this.CreateChartRefresh()
        }
      });
    },
    CreateChartRefresh() {
      setTimeout(() => {
        this.$nextTick(() => {
          this.ChangeSize();
          if (this.current === 0) {
            this.CreateMinuteChart();
          } else {
            this.CreateKLineChart();
          }
        });
      }, 300);
    },
    //切换指标 windowId=窗口索引 name=指标名字
    ChangeKLineIndex: function (windowId, name) {
      if (!g_JSChart) return;
      if (this.IsKLineChart(g_JSChart)) g_JSChart.ChangeIndex(windowId, name);
    },
    ChangeSize() {
      // #ifdef H5
      this.ChangeSize_h5();
      // #endif
      // #ifndef H5
      this.ChangeSize_app();
      // #endif
    },
    CreateMinuteChart() {
      // #ifdef H5
      this.CreateMinuteChart_h5();
      // #endif
      // #ifndef H5
      this.CreateMinuteChart_app();
      // #endif
    },
    CreateKLineChart() {
      // #ifdef H5
      this.CreateKLineChart_h5();
      // #endif

      // #ifndef H5
      this.CreateKLineChart_app();
      // #endif
    },
    ChangeSize_h5() {
      var chartHeight = this.ChartHeight;
      var chartWidth = this.ChartWidth;
      var kline = this.$refs.kline;
      kline.style.width = chartWidth + 'px';
      kline.style.height = chartHeight + 'px';
      if (g_JSChart) g_JSChart.OnSize();
    },
    ChangeSize_app() {
      if (g_JSChart) {
        //把画布大小设置到hqchart
        g_JSChart.OnSize({
          Width: this.ChartWidth,
          Height: this.ChartHeight,
          Type: 1
        }); //重新绘制
      }
    },

    //创建日线图
    CreateMinuteChart_h5() {
      this.ClearChart();
      var blackStyle = HQChart.HQChartStyle.GetStyleConfig(HQChart.STYLE_TYPE_ID.WHITE_ID);
      HQChart.JSChart.SetStyle(blackStyle);
      this.$refs.kline.style.backgroundColor = blackStyle.BGColor; //div背景色设置黑色

      var chart = HQChart.JSChart.Init(this.$refs.kline);
      var option = DefaultData.GetMinuteOption();
      option.Symbol = this.Symbol;
      option.NetworkFilter = this.NetworkFilter;
      // 日线 1  周线:2 月线 3 1分钟 4 5分钟 5 30分钟 6  60分钟  7  4小时 8
      option.DayCount = 1;
      // option.DayCount = this.current === 1 ? this.newfen.num : this.current - 1;
      chart.SetOption(option);
      chart.AddEventCallback({
        event: HQChart.JSCHART_EVENT_ID.ON_TITLE_DRAW,
        callback: this.OnTitleDraw
      });
      g_JSChart = chart;
    },
    CreateMinuteChart_app() {
      this.ClearChart();
      var element = new JSCommon.JSCanvasElement();
      // #ifdef APP-PLUS
      element.IsUniApp = true; //canvas需要指定下 是uniapp的app
      // #endif
      element.ID = 'kline2';
      element.Height = this.ChartHeight; //高度宽度需要手动绑定!!
      element.Width = this.ChartWidth;
      //用黑色风格
      var blackStyle = JSCommonHQStyle.GetStyleConfig(JSCommonHQStyle.STYLE_TYPE_ID.WHITE_ID);
      JSCommon.JSChart.SetStyle(blackStyle);
      //var testttt=JSCommon.MARKET_SUFFIX_NAME.GetSHODecimal();
      //JSCommon.MARKET_SUFFIX_NAME.GetSHODecimal=(symbol)=>{ return 4; };	//设置期权代码

      var chart = JSCommon.JSChart.Init(element);
      var option = DefaultData.GetMinuteOption();
      option.NetworkFilter = this.NetworkFilter;
      option.Symbol = this.Symbol;
      // 日线 1  周线:2 月线 3 1分钟 4 5分钟 5 30分钟 6  60分钟  7  4小时 8
      option.DayCount = 1;
      // option.DayCount = this.current === 1 ? this.newfen.num : this.current - 1;
      option.IsFullDraw = true; //每次手势移动全屏重绘
      chart.SetOption(option);
      //chart.AddEventCallback({ event: JSCommon.JSCHART_EVENT_ID.ON_TITLE_DRAW, callback: this.OnMinuteTitleDraw });

      chart.AddEventCallback({
        event: JSCommon.JSCHART_EVENT_ID.ON_PHONE_TOUCH,
        callback: this.OnPhoneTouch
      });

      g_JSChart = chart;
    },
    CreateKLineChart_h5() { //创建K线图
      this.ClearChart();
      var blackStyle = HQChart.HQChartStyle.GetStyleConfig(HQChart.STYLE_TYPE_ID.WHITE_ID);
      HQChart.JSChart.SetStyle(blackStyle);
      this.$refs.kline.style.backgroundColor = blackStyle.BGColor; //div背景色设置黑色

      var chart = HQChart.JSChart.Init(this.$refs.kline);
      var option = DefaultData.GetKLineOption();
      option.Symbol = this.Symbol;
      option.KLine.Right = this.KLine.Right;
      // option.KLine.Period = this.KLine.Period;
      // 日线 1  周线:2 月线 3 1分钟 4 5分钟 5 30分钟 6  60分钟  7  4小时 8
      option.KLine.Period =
        this.current === 1 ? this.newfen.num : this.current === 2 ? 0 : this.current === 3 ? 1 : 2;
      // option.DayCount = this.current === 1 ? this.newfen.num : this.current - 1;
      option.NetworkFilter = this.NetworkFilter;
      chart.SetOption(option);
      chart.AddEventCallback({
        event: HQChart.JSCHART_EVENT_ID.ON_TITLE_DRAW,
        callback: this.OnTitleDraw
      });

      g_JSChart = chart;
    },
    CreateKLineChart_app() {
      this.ClearChart();
      var element = new JSCommon.JSCanvasElement();
      // #ifdef APP-PLUS
      element.IsUniApp = true; //canvas需要指定下 是uniapp的app
      // #endif
      element.ID = 'kline2';
      element.Height = this.ChartHeight; //高度宽度需要手动绑定!!
      element.Width = this.ChartWidth;
      // 不同风格行情
      var blackStyle = JSCommonHQStyle.GetStyleConfig(JSCommonHQStyle.STYLE_TYPE_ID.WHITE_ID);
      //blackStyle.DefaultTextColor='rgb(255,0,255)';
      JSCommon.JSChart.SetStyle(blackStyle);
      var chart = JSCommon.JSChart.Init(element);
      var option = DefaultData.GetKLineOption();
      option.NetworkFilter = this.NetworkFilter;
      option.Symbol = this.Symbol;
      option.KLine.Right = this.KLine.Right;
      // option.KLine.Period = this.KLine.Period;
      // 日线 1  周线:2 月线 3 1分钟 4 5分钟 5 30分钟 6  60分钟  7  4小时 8
      option.KLine.Period =
        this.current === 1 ? this.newfen.num : this.current === 2 ? 0 : this.current === 3 ? 1 : 2;
      // option.DayCount = this.current === 1 ? this.newfen.num : this.current - 1;
      option.IsClickShowCorssCursor = true;
      option.IsFullDraw = true; //每次手势移动全屏重绘
      chart.SetOption(option);
      //chart.AddEventCallback( { event:JSCommon.JSCHART_EVENT_ID.RECV_INDEX_DATA, callback:this.OnRecvHistoryData });
      chart.AddEventCallback({
        event: JSCommon.JSCHART_EVENT_ID.ON_TITLE_DRAW,
        callback: this.OnTitleDraw
      });

      g_JSChart = chart;
    },
    IsKLineChart() {
      if (!g_JSChart) return false;
      var className = g_JSChart.JSChartContainer.ClassName;
      if (className == 'KLineChartContainer' || className == 'KLineChartHScreenContainer')
        return true;

      return false;
    },
    NetworkFilter: function (data, callback) {
      if (data.Name == 'APIScriptIndex::ExecuteScript') {
        this.CustomIndex(data, callback);
      } else {
        HQData.HQData.NetworkFilter(data, callback);
      }
    },
    //自定义指标
    CustomIndex(data, callback) {
      var request = data.Request;
      if (request.Data.indexname == '多线段指标') {
        data.PreventDefault = true;

        var hqchart = data.HQChart;
        var kData = hqchart.ChartPaint[0].Data;
        var closeLine = {
          name: '收盘价线',
          type: 0,
          data: kData.GetClose()
        };
        var klineDate = kData.GetDate();

        //模拟异步请求指标数据
        setTimeout(function () {
          var apiData = {
            code: 0,
            stock: {
              name: hqchart.Name,
              symbol: hqchart.Symbol
            },
            outdata: {
              date: klineDate,
              outvar: [closeLine]
            }
          };
          console.log('[NetworkFilter::NetworkFilter] apiData ', apiData);
          callback(apiData);
        }, 200);
      }
    },
    //K线信息
    OnTitleDraw(event, data, obj) {
      console.log('[K线信息]', event, data);
    },
    OnPhoneTouch(event, data, obj) {
      console.log('[滑动点]', data);
    },
    //手势事件 app/小程序才有
    //KLine事件
    KLineTouchStart: function (event) {
      if (g_JSChart) g_JSChart.OnTouchStart(event);
    },

    KLineTouchMove: function (event) {
      if (g_JSChart) g_JSChart.OnTouchMove(event);
    },

    KLineTouchEnd: function (event) {
      if (g_JSChart) g_JSChart.OnTouchEnd(event);
    },
    ClearChart() {
      if (g_JSChart) {
        g_JSChart.ChartDestory();
        g_JSChart = null;
      }

      // #ifdef H5
      var divKLine = document.getElementById('kline');
      while (divKLine.hasChildNodes()) {
        divKLine.removeChild(divKLine.lastChild);
      }
      // #endif
    }
  }
};